<?php
namespace app\auto\controller;

use app\BaseController;
use PhpOffice\PhpWord\PhpWord;
use think\facade\View;
use think\facade\Db;
use think\facade\Config;

class DbDoc extends BaseController
{

    /**
     * @return string
     * @throws \PhpOffice\PhpWord\Exception\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        if (request()->isPost()) {
            $is_other = input('is_other');
            if($is_other){
                $config = Config::get('database');
                $config['connections']['tmp'] = [
                    'type' => 'mysql',
                    'hostname' => input('ip'),
                    'database' => input('name'),
                    'username' => input('user'),
                    'password' => input('pwd'),
                    'hostport' => input('port'),
                    'params' => [],
                    'charset' => 'utf8'
                ];
                Config::set($config, 'database');
            }


            $dbs = input('dbs');


            $phpWord = new PhpWord();

            $phpWord->addNumberingStyle(
                'multilevel',
                array(
                    'type' => 'multilevel',
                    'levels' => array(
                        array('format' => 'decimal', 'text' => '%1', 'left' => 360, 'hanging' => 360, 'tabPos' => 360),
                        array('format' => 'decimal', 'text' => '%1.%2', 'left' => 720, 'hanging' => 360, 'tabPos' => 720),
                    )
                )
            );

            $fontStyleHeader2 = array('bold' => true, 'align' => 'left', 'size' => 16);
            $fontStyleHeader1 = array('bold' => true, 'align' => 'left', 'size' => 18);
            $section = $phpWord->addSection();
            $section->addTOC([], [], 2, 2);
            $phpWord->addTitleStyle(2, $fontStyleHeader2);
            $phpWord->addTitleStyle(1, $fontStyleHeader1);


            $styleTable = array(
                'borderSize' => 6,
                'borderColor' => '006699',
                'cellMargin' => 80
            );
            $styleFirstRow = array(
                'borderBottomSize' => 18,
                'borderBottomColor' => '0000ff',
                'bgColor' => '66bbff'
            );
            //定义单元格样式数组
            $styleCell = array('valign' => 'center');
//        $styleCellBTLR = array('valign'=>'center','textDirection'=>PhpWord_Style_Cell::TEXT_DIR_BTLR);


            //定义第一行的字体
            $fontStyle = array('bold' => true, 'align' => 'center', 'size' => 8);
            $fontStyle1 = array('bold' => false, 'align' => 'center', 'size' => 6);


            //添加表格样式
            $phpWord->addTableStyle('myOwnTableStyle', $styleTable, $styleFirstRow);


            $section = $phpWord->addSection();

//        $section->addListItem('', 0, null, 'multilevel');
            $section->addTitle('各级表机构描述', 1);
            $section->addText('');
            $section->addText('');
            $section->addText('');
            $section->addText('');

            if($is_other){
                $res = Db::connect('tmp')->table('INFORMATION_SCHEMA.TABLES')->where('TABLE_SCHEMA', input('name'))->field('table_name,table_comment')->select()->toArray();
            }else{
                $res = Db::table('INFORMATION_SCHEMA.TABLES')->where('TABLE_SCHEMA', input('name'))->field('table_name,table_comment')->select()->toArray();

            }

            foreach ($res as $k => $v) {

                if (in_array($v['table_name'], $dbs)) {
//                    $section->addListItem('', 1, null, 'multilevel');
                    $section->addTitle( $v[table_comment]. ' ' .$v[table_name] , 2);
                    //添加表格
                    $table = $section->addTable('myOwnTableStyle');
                    //添加行
                    $table->addRow(200);
                    //添加单元格
                    $table->addCell(1000, $styleCell)->addText('字段名', $fontStyle);
                    $table->addCell(1000, $styleCell)->addText('数据类型及长度', $fontStyle);
                    $table->addCell(1000, $styleCell)->addText('是否主键', $fontStyle);
                    $table->addCell(1000, $styleCell)->addText('允许空', $fontStyle);
                    $table->addCell(1000, $styleCell)->addText('默认值', $fontStyle);
                    $table->addCell(1000, $styleCell)->addText('字段中文名', $fontStyle);

                    if($is_other){
                        $all = Db::connect('tmp')->query('SHOW FULL COLUMNS FROM ' . $v['table_name']);
                    }else{
                        $all = Db::query('SHOW FULL COLUMNS FROM ' . $v['table_name']);
                    }
                    foreach ($all as $val) {
                        $table->addRow(200);
                        $table->addCell(1000)->addText($val['Field'], $fontStyle1);
                        $table->addCell(1000)->addText($val['Type'], $fontStyle1);
                        $table->addCell(1000)->addText($val['Key'], $fontStyle1);
                        $table->addCell(1000)->addText($val['Null'], $fontStyle1);
                        $table->addCell(1000)->addText($val['Default'], $fontStyle1);
                        $table->addCell(1000)->addText($val['Comment'], $fontStyle1);
                    }
                    $v['all'] = $val;
                    $res[$k] = $v;
                    $section->addText('');
                    $section->addText('');
                    $section->addText('');
                    $section->addText('');
                }

            }

            $filename = input('filename', '');
            $file = $filename . '数据库文档.docx';
            ob_end_clean();
            ob_start();
            header("Content-Description: File Transfer");
            header('Content-Disposition: attachment; filename="' . $file . '"');
            header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
            header('Content-Transfer-Encoding: binary');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Expires: 0');
            $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
            $xmlWriter->save("php://output");
            exit;
        } else {
            $database = config('database.connections.mysql.database');
            View::assign('database', $database);
            return View::fetch();
        }

    }

    /**
     * 获取数据表
     */
    public function getTables(): \think\response\Json
    {
        $is_other = input('is_other');
        $config = Config::get('database');
        $config['connections']['tmp'] = [
            'type' => 'mysql',
            'hostname' => input('ip'),
            'database' => input('name'),
            'username' => input('user'),
            'password' => input('pwd'),
            'hostport' => input('port')?:3306,
            'params' => [],
            'charset' => 'utf8'
        ];
        Config::set($config, 'database');
        $data = [];
        try {
            if($is_other){
                $data = Db::connect('tmp')->query('show tables');
            }else{
                $data = Db::query('show tables');
            }
        } catch (\Exception $e) {
            if ($e->getMessage()) {
                return error($e->getMessage());
            }
        }
        $res = [];
        foreach ($data as  $item) {
            foreach ($item as  $table_name){
                $res[] = $table_name;
            }
        }
        return success('ok',$res);

    }

}
